package com.young.jdbc;

import com.young.jdbc.myjdbc.JdbcUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author: young
 * @Date: 2021-12-03 11:42
 * @Description: 在JDBC中使用事务
 */
public class Transaction_demo {
	@Test
	public void noTransaction(){
		Connection connection = null;
		String sql1 = "update account set balance = balance - 100 where id = 1";
		String sql2 = "update account set balance = balance + 100 where id = 2";
		PreparedStatement preparedStatement = null;

		try {
			connection = JdbcUtils.getConnection();	// 默认情况下，connection是自动提交的
			preparedStatement = connection.prepareStatement(sql1);
			preparedStatement.executeUpdate();
			int i = 1/0; // 抛出异常
			preparedStatement = connection.prepareStatement(sql2);
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.close(null,preparedStatement,connection);
		}

	}
	@Test
	public void useTransaction(){
		Connection connection = null;
		String sql1 = "update account set balance = balance - 100 where id = 1";
		String sql2 = "update account set balance = balance + 100 where id = 2";
		PreparedStatement preparedStatement = null;

		try {
			connection = JdbcUtils.getConnection();	// 默认情况下，connection是自动提交的
			// 将connection设置为不自动提交
			connection.setAutoCommit(false);	//事务开始的地方
			preparedStatement = connection.prepareStatement(sql1);
			preparedStatement.executeUpdate();
			int i = 1/0; // 抛出异常
			preparedStatement = connection.prepareStatement(sql2);
			preparedStatement.executeUpdate();

			// 提交事务
			connection.commit();
		} catch (SQLException e) {
			// 在这里可以进行回滚，即撤销执行的SQL
			// 默认回滚到事务开始的地方
			try {
				connection.rollback();
			} catch (SQLException throwables) {
				throwables.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			JdbcUtils.close(null,preparedStatement,connection);
		}

	}
}
